﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Security.Principal;
using Universum.Infrastructure.Persistence;
using Universum.Model.Domain;

namespace Universum.Model.Services
{
	public class RssServiceImpl:
		IRssService
	{
		IPrincipal _Principal;
		IRepository _Repository;
		public RssServiceImpl(
			IPrincipal principal,
			IRepository repository
			)
		{
			_Principal = principal;
			_Repository = repository;
			
		}
		#region IRssService Members

		public string GenerateRssContent()
		{
			var rss =  new XDocument(
				new XDeclaration("1.0","utf-8",null),
					new XElement("rss",new XAttribute("version","2.0"),
						new XElement("channel",
							new XElement("title","Universum publications"),
							new XElement("link","Rss/Content"),
							new XElement("description",
								@"Universum is a community of students and teacher that wants only
to share knowledge"),
							new XElement("ttl","120"),
							new XElement("name","Universum"),
							new XElement("user", _Principal.Identity.Name),
							new XElement("pubDate", DateTime.Now.ToUniversalTime()),
							new XElement("lastBuildDate",DateTime.Now.ToUniversalTime()),
							new XElement("webMaster","lazar.florinmihai@gmail.com")
							
							)
						)
					);

			AddItems(rss.Element("rss").Element("channel"));
			return rss.ToString( );

				
		}

		private void  AddItems(XElement element)
		{
			var last25Items = _Repository.Query<Article>().Where(it => it.Publish <= DateTime.Now).OrderByDescending(it => it.Created).Take(25).ToList();
			
			last25Items.ForEach(
				it =>
				{
					element.Add(GetItem(it));
					
				});
			
		}

		private XElement GetItem(Article it)
		{
			return new XElement("item",
					new XElement("title", it.Title),
					new XElement("description", it.Text),
					new XElement("link",
						null)
					);
			
		}

	

		#endregion
	}
}
